//
//  DYDiscoViewController.m
//  colorTest
//
//  Created by 丁益 on 2017/4/2.
//  Copyright © 2017年 celi. All rights reserved.
//  
#import <AVFoundation/AVFoundation.h>
#import "DYDiscoViewController.h"
#import "CLSeverTool.h"
#import <AVFoundation/AVFoundation.h>
#import "YSCVoiceWaveView.h"
#import "YSCVoiceLoadingCircleView.h"
#import "SendWifiDataTool.h"
#import "YSCNewVoiceWaveView.h"

@interface DYDiscoViewController ()
{
    SendWifiDataTool *_sendSingleColor;
}

@property (nonatomic,weak) UIButton *micrBtn;

@property (nonatomic, strong) AVAudioRecorder *recorder;
@property (nonatomic, strong) YSCVoiceWaveView *voiceWaveView;
@property (nonatomic, strong) UIView *voiceWaveParentView;
@property (nonatomic, strong) YSCVoiceLoadingCircleView *loadingView;
@property (nonatomic, strong) NSTimer *updateVolumeTimer;
@property (nonatomic, strong) UIButton *voiceWaveShowButton;

@property (nonatomic, strong) YSCNewVoiceWaveView *voiceWaveViewNew;
@property (nonatomic, strong) UIView *voiceWaveParentViewNew;
@property (nonatomic, weak) UISlider *speedSlider;

@end

@implementation DYDiscoViewController

- (void)dealloc
{
    [_voiceWaveView removeFromParent];
    [_loadingView stopLoading];
    _voiceWaveView = nil;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"DISCO";
    
    [self setupRecorder];
    
    self.view.backgroundColor = [UIColor whiteColor];
    //[self applyAVAudioLimits];
    
    //显示灵明度
    [self creatSlider];
    
    //显示提示语
    [self creatMicroTitle];
    
    //显示话筒图标
    [self creatMicrophone];
    
    [self.view insertSubview:self.voiceWaveParentView atIndex:0];
    [self.voiceWaveView showInParentView:self.voiceWaveParentView];
    [self.voiceWaveView startVoiceWave];
    
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    //[self.view insertSubview:self.voiceWaveParentViewNew atIndex:1];
    //[self.voiceWaveViewNew showInParentView:self.voiceWaveParentViewNew];
    //[self.voiceWaveViewNew startVoiceWave];
    
//    [[NSRunLoop currentRunLoop] addTimer:self.updateVolumeTimer forMode:NSRunLoopCommonModes];
    
    SendWifiDataTool *sendSingleColor = [SendWifiDataTool sharedSendWifiDataTool];
    _sendSingleColor = sendSingleColor;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.updateVolumeTimer invalidate];
    _updateVolumeTimer = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSRunLoop currentRunLoop] addTimer:self.updateVolumeTimer forMode:NSRunLoopCommonModes];
}

- (void)creatSlider
{
    CGFloat speedSliderY = sHeight - 49 - 60 - 50;
    UISlider *speedSlider = [[UISlider alloc]initWithFrame:CGRectMake(30, speedSliderY,sWidth-60, 20)];
    speedSlider.value = 0.5;
    [speedSlider addTarget:self action:@selector(speedSliderChanged:) forControlEvents:UIControlEventValueChanged];
    self.speedSlider = speedSlider;
    [self.view addSubview:speedSlider];
    
    CGFloat labelY = CGRectGetMaxY(speedSlider.frame);
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, labelY, 80, 30)];
    label.centerX = sWidth/2;
    label.text = @"灵明度";
    label.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:label];
}



- (void)speedSliderChanged:(UISlider*)slider
{
    DLog(@"sliderValue = %f",slider.value);
    [self.voiceWaveView changeVolume:slider.value];
}

//显示提示语
- (void)creatMicroTitle
{
    CGFloat space = 10;
    CGFloat titleY = sHeight - 49 - 60;
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(space, titleY, sWidth-2*space, 50)];
    title.numberOfLines = 0;
    [title setFont:[UIFont systemFontOfSize:13]];
    title.text = @"提示:您可以按“Home”，然后使用其他音乐播放器播放音乐，这样您的灯就会随着音乐跳动。";
    [self.view addSubview:title];
}

//显示话筒图标
- (void)creatMicrophone
{
    CGFloat micrBtnY = self.speedSlider.y - 60-10;
    UIButton *micrBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, micrBtnY, 60, 60)];
    [micrBtn setImage:[UIImage imageNamed:@"img_mic_on"] forState:UIControlStateNormal];
    [micrBtn setImage:[UIImage imageNamed:@"img_mic_off"] forState:UIControlStateSelected];
    micrBtn.centerX = sWidth/2;
    [micrBtn addTarget:self action:@selector(micrBtnOnclik:) forControlEvents:UIControlEventTouchUpInside];
    self.micrBtn = micrBtn;
    [self.view addSubview:micrBtn];
}



- (void)micrBtnOnclik:(UIButton *)btn
{
    self.micrBtn.selected = !btn.selected;
    
    static NSInteger status = 1;
    status++;
    if (status % 2 == 0) {
        [_voiceWaveShowButton setTitle:@"show" forState:UIControlStateNormal];
        [self.voiceWaveView stopVoiceWaveWithShowLoadingViewCallback:^{
            [self.updateVolumeTimer invalidate];
            _updateVolumeTimer = nil;
            [self.loadingView startLoadingInParentView:self.view];
        }];
    } else {
        [_voiceWaveShowButton setTitle:@"hide" forState:UIControlStateNormal];
        [self.loadingView stopLoading];
        [self.voiceWaveView showInParentView:self.voiceWaveParentView];
        [self.voiceWaveView startVoiceWave];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)updateVolume:(NSTimer *)timer
{
    static int  count = 0;
    [self.recorder updateMeters];
    CGFloat normalizedValue = pow (10, [self.recorder averagePowerForChannel:0] / 20);
    
    
    
    count ++ ;
    if (count == 1) {
        count = 0;
        CGFloat voiceValue = normalizedValue*256;
        NSString *redValue = [NSString stringWithFormat:@"%0.0f",voiceValue];
        
        NSString *greenValue = nil;
        if (voiceValue > 255) {
            greenValue = @"0";
        } else {
            greenValue = [NSString stringWithFormat:@"%0.0f",(255-voiceValue)];
        }
        
        NSString *blueValue = nil;
        if (voiceValue > 180) {
            blueValue = @"0";
        } else {
            blueValue = [NSString stringWithFormat:@"%0.0f",(180 - voiceValue)];
        }
        
        [_sendSingleColor  sendSingleRGBColorCmdRedValue: redValue blueValue:blueValue greenValue:greenValue];
    }
    
    [_voiceWaveView changeVolume:normalizedValue];
    
    [_voiceWaveViewNew changeVolume:normalizedValue];
}

-(void)setupRecorder
{
    NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
    NSDictionary *settings = @{AVSampleRateKey:          [NSNumber numberWithFloat: 44100.0],
                               AVFormatIDKey:            [NSNumber numberWithInt: kAudioFormatAppleLossless],
                               AVNumberOfChannelsKey:    [NSNumber numberWithInt: 2],
                               AVEncoderAudioQualityKey: [NSNumber numberWithInt: AVAudioQualityMin]};
    
    NSError *error;
    self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
    if(error) {
        DLog(@"Ups, could not create recorder %@", error);
        return;
    }
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    if (error) {
        DLog(@"Error setting category: %@", [error description]);
    }
    [self.recorder prepareToRecord];
    [self.recorder setMeteringEnabled:YES];
    [self.recorder record];
}


#pragma mark - getters

- (YSCVoiceWaveView *)voiceWaveView
{
    if (!_voiceWaveView) {
        self.voiceWaveView = [[YSCVoiceWaveView alloc] init];
    }
    
    return _voiceWaveView;
}

- (UIView *)voiceWaveParentView
{
    if (!_voiceWaveParentView) {
        self.voiceWaveParentView = [[UIView alloc] init];
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        _voiceWaveParentView.frame = CGRectMake(0, 0, screenSize.width, sWidth);
        //        _voiceWaveParentView.center = CGPointMake(self.view.bounds.size.width / 2.0, self.view.bounds.size.height / 2.0);
    }
    
    return _voiceWaveParentView;
}

- (YSCNewVoiceWaveView *)voiceWaveViewNew
{
    if (!_voiceWaveViewNew) {
        self.voiceWaveViewNew = [[YSCNewVoiceWaveView alloc] init];
        [_voiceWaveViewNew setVoiceWaveNumber:6];
    }
    
    return _voiceWaveViewNew;
}

- (UIView *)voiceWaveParentViewNew
{
    if (!_voiceWaveParentViewNew) {
        self.voiceWaveParentViewNew = [[UIView alloc] init];
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        _voiceWaveParentViewNew.frame = CGRectMake(0, 330, screenSize.width, 320);
        //        _voiceWaveParentViewNew.center = CGPointMake(self.view.bounds.size.width / 2.0, self.view.bounds.size.height / 2.0);
    }
    
    return _voiceWaveParentViewNew;
}

- (YSCVoiceLoadingCircleView *)loadingView
{
    if (!_loadingView) {
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        CGPoint loadViewCenter = CGPointMake(screenSize.width / 2.0, 160);
        self.loadingView = [[YSCVoiceLoadingCircleView alloc] initWithCircleRadius:25 center:loadViewCenter];
    }
    
    return _loadingView;
}



- (NSTimer *)updateVolumeTimer
{
    if (!_updateVolumeTimer) {
        self.updateVolumeTimer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(updateVolume:) userInfo:nil repeats:YES];
    }
    return _updateVolumeTimer;
}
@end
